﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OES.Models;
using System.IO;
using OES.ViewModels;
using PagedList;
using WebMatrix.WebData;

namespace OES.Controllers
{
    [Authorize]
    public class ExamController : Controller
    {
        private DataContext db = new DataContext();

        //
        // GET: /Exam/
        [HttpGet]
        public ActionResult Index(int? id)
        {
            //if (db.Courses.Find(id).UserID != WebSecurity.CurrentUserId)
            //    return View();
            var courses = db.Courses.Where(c => c.UserID == WebSecurity.CurrentUserId).OrderBy(c => c.Name);
            ViewBag.CourseId = new SelectList(courses, "CourseId", "Name", id);
            var exams = db.Exams.Include(e => e.course).Include(q => q.Questions).Where(e => e.CourseID == id);
            return View(exams.ToList());

        }

        //
        // GET: /Exam/Details/5

        //public ActionResult Details(int id = 0)
        //{
        //    Exam exam = db.Exams.Find(id);
        //    if (exam == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    return View(exam);
        //}

        public ActionResult Details(int id = 0)
        {
            Exam exam = db.Exams.Find(id);
            if (exam == null)
            {
                return HttpNotFound();
            }
            return View(exam);
        }


        [HttpGet]
        public ActionResult Soru(int? page, int id = 0)
        {
            Exam exam = db.Exams.Find(id);
            if (exam == null)
            {
                return HttpNotFound();
            }
            ViewBag.ExamId = exam.ExamId;

            var questions = db.Questions.Include(q => q.Choices).Where(c => c.ExamId == id).OrderBy(c => c.ExamId);
            int pageSize = 3;
            ViewBag.PageSize = pageSize;

            int pageNumber = (page ?? 1);
            ViewBag.PageNumber = pageNumber;
            return View(questions.ToPagedList(pageNumber, pageSize));
        }
        //
        // GET: /Exam/Create

        public ActionResult Create()
        {
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Name");
            return View();
        }

        //
        // POST: /Exam/Create

        [HttpPost]
        public ActionResult Create(Exam exam)
        {
            if (ModelState.IsValid)
            {
                db.Exams.Add(exam);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Name", exam.CourseID);
            return View(exam);
        }

        //
        // GET: /Exam/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Exam exam = db.Exams.Find(id);
            if (exam == null)
            {
                return HttpNotFound();
            }
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Name", exam.CourseID);
            return View(exam);
        }




        //
        // POST: /Exam/Edit/5

        [HttpPost]
        public ActionResult Edit(Exam exam)
        {
            if (ModelState.IsValid)
            {
                db.Entry(exam).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Name", exam.CourseID);
            return View(exam);
        }

        //
        // GET: /Exam/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Exam exam = db.Exams.Find(id);
            if (exam == null)
            {
                return HttpNotFound();
            }
            return View(exam);
        }

        //
        // POST: /Exam/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Exam exam = db.Exams.Find(id);
            db.Exams.Remove(exam);
            db.SaveChanges();
            return RedirectToAction("Index");
        }




        public ActionResult AddQuestion(int id = 0)
        {

            ViewBag.ExamId = id;//new SelectList(db.Exams, "ExamId", "ExamId",id);
            ViewBag.Question_TypeId = new SelectList(db.Question_Types, "Question_TypeId", "Question_TypeName");
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddQuestion(Question q, string[] RightChoice, string[] ChoiceText)
        {

            if (ModelState.IsValid)
            {
         
                db.Questions.Add(q);
                db.SaveChanges();
                for (int i = 0; i < ChoiceText.Length; i++)
                {
                    db.Choices.Add(new Choice { ChoiceText = ChoiceText[i], QuestionId = q.QuestionId, TrueAnswer = RightChoice.Contains(i.ToString()) == true ? true : false });
                    db.SaveChanges();
                }
                return RedirectToAction("Index");
            }
            ViewBag.Question_TypeId = new SelectList(db.Question_Types, "Question_TypeId", "Question_TypeName", q.Question_TypeId);
            return View(q);
        


        }
        [HttpPost]
        public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor, string langCode)
        {
            string vImagePath = String.Empty;
            string vMessage = String.Empty;
            string vFilePath = String.Empty;
            string vOutput = String.Empty;

            try
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") +
                                    Path.GetExtension(upload.FileName).ToLower();
                    var vFolderPath = Server.MapPath("~/deneme");

                    if (!Directory.Exists(vFolderPath))
                    {
                        Directory.CreateDirectory(vFolderPath);
                    }

                    vFilePath = Path.Combine(vFolderPath, vFileName);
                    upload.SaveAs(vFilePath);

                    vImagePath = Url.Content("~/deneme/" + vFileName);
                    vMessage = "Image was saved correctly";
                }
            }
            catch
            {
                vMessage = "There was an issue uploading";
            }

            vOutput = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";

            return Content(vOutput);

        }
        public ActionResult BrowseImage(string CKEditorFuncNum, string CKEditor, string langCode)
        {
            var vFolderPath = Server.MapPath("~/deneme/");
            var vBrowseViewModel = new AdminBrowseImageViewModel { CKEditorFuncNum = CKEditorFuncNum };

            if (Directory.Exists(vFolderPath))
            {
                vBrowseViewModel.ImagePaths = Directory.GetFiles(vFolderPath).Select(p => Url.Content("~/deneme/" + Path.GetFileName(p))).ToList();
            }

            return View(vBrowseViewModel);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}